<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="客户编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入客户编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['customer:customer:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['customer:customer:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['customer:customer:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['customer:customer:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['customer:customer:import']"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="customerList"
      @selection-change="handleSelectionChange"
      highlight-current-row
      :row-class-name="tableRowClassName"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="客户编码" align="center" prop="code" />
      <el-table-column label="客户名称" align="center" prop="name" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="是否启用" align="center" prop="enable">
        <template #default="scope">
          <el-tag :type="scope.row.enable === 1 ? 'success' : 'info'">
            {{ scope.row.enable === 1 ? "启用" : "停用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="助记码" align="center" prop="cusColumn0" />
      <el-table-column label="客户类别" align="center" prop="cusColumn1" />
      <el-table-column label="经营地址" align="center" prop="cusColumn2" />
      <el-table-column label="联系人" align="center" prop="cusColumn3" />
      <el-table-column label="手机号" align="center" prop="cusColumn4" />
      <el-table-column label="税号" align="center" prop="cusColumn5" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['customer:customer:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['customer:customer:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="customerRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="客户编码" prop="code">
          <el-input v-model="form.code" placeholder="自动生成编码" />
        </el-form-item>
        <el-form-item label="客户名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入客户名称"
            @input="handleNameInput"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="助记码" prop="cusColumn0">
          <el-input
            v-model="form.cusColumn0"
            placeholder="自动生成助记码"
            readonly
          />
        </el-form-item>
        <el-form-item label="客户类别" prop="cusColumn1">
          <el-input v-model="form.cusColumn1" placeholder="请输入客户类别" />
        </el-form-item>
        <el-form-item label="经营地址" prop="cusColumn2">
          <div class="address-select">
            <el-select
              v-model="selectedProvince"
              placeholder="请选择省份"
              clearable
              @change="handleProvinceChange"
              style="width: 150px; margin-right: 10px"
            >
              <el-option
                v-for="item in provinceOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              v-model="selectedCity"
              placeholder="请选择城市"
              clearable
              :disabled="!selectedProvince"
              @change="handleCityChange"
              style="width: 150px; margin-right: 10px"
            >
              <el-option
                v-for="item in cityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              v-model="selectedArea"
              placeholder="请选择区域"
              clearable
              :disabled="!selectedCity"
              @change="handleAreaChange"
              style="width: 150px"
            >
              <el-option
                v-for="item in areaOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <el-input
            v-model="detailAddress"
            placeholder="请输入详细地址"
            style="margin-top: 10px"
            @input="handleDetailAddressChange"
          />
          <el-input
            v-model="fullAddress"
            placeholder="完整地址"
            readonly
            style="margin-top: 10px"
          >
            <template #prepend>
              <el-icon><Location /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="cusColumn3">
          <el-input v-model="form.cusColumn3" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="手机号" prop="cusColumn4">
          <el-input v-model="form.cusColumn4" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="税号" prop="cusColumn5">
          <el-input v-model="form.cusColumn5" placeholder="请输入税号" />
        </el-form-item>
        <el-form-item label="是否启用" prop="enable">
          <el-switch
            v-model="form.enable"
            active-text="启用"
            inactive-text="停用"
            :active-value="1"
            :inactive-value="0"
            @change="handleEnableChange"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加导入对话框 -->
    <el-dialog
      v-model="importOpen"
      title="导入客户数据"
      width="400px"
      append-to-body
      :close-on-click-modal="false"
      @closed="handleImportDialogClosed"
    >
      <el-form ref="uploadFormRef" :model="data.uploadForm" label-width="80px">
        <el-form-item label="Excel文件">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept=".xlsx, .xls"
            :before-upload="handleBeforeUpload"
            :http-request="handleUpload"
            :on-exceed="handleExceed"
            :on-change="handleFileChange"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip text-center">
                <div>仅允许导入xlsx、xls格式文件，文件大小不超过5MB</div>
                <el-link
                  type="primary"
                  :underline="false"
                  style="font-size: 12px; margin-left: 12px"
                  @click="importTemplate"
                  >下载模板</el-link
                >
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm" :loading="uploading"
            >确 定</el-button
          >
          <el-button @click="importOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Customer">
import {
  listCustomer,
  getCustomer,
  delCustomer,
  addCustomer,
  updateCustomer,
  importCustomer,
} from "@/api/customer/customer";
import { ElMessage } from "element-plus";
import {
  getProvinceList,
  getChildrenByParentId,
} from "@/api/customer/customer";
import { Location } from "@element-plus/icons-vue";

const { proxy } = getCurrentInstance();

const customerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const importOpen = ref(false);
const uploadRef = ref(null);
const fileList = ref([]);
const uploading = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: null,
    name: null,
  },
  rules: {
    code: [{ required: true, message: "客户编码不能为空", trigger: "blur" }],
    name: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
    cusColumn4: [
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
  uploadForm: {},
});

const { queryParams, form, rules } = toRefs(data);

// 地址相关数据
const selectedProvince = ref("");
const selectedCity = ref("");
const selectedArea = ref("");
const detailAddress = ref("");
const provinceOptions = ref([]);
const cityOptions = ref([]);
const areaOptions = ref([]);
const fullAddress = ref(""); // 新增完整地址显示

// 初始化省份数据
onMounted(async () => {
  try {
    const res = await getProvinceList();
    provinceOptions.value = res.data.map((item) => ({
      value: item.id,
      label: item.name,
    }));
  } catch (error) {
    console.error("获取省份列表失败:", error);
  }
});

// 处理省份选择变化
const handleProvinceChange = async (value) => {
  selectedCity.value = "";
  selectedArea.value = "";
  cityOptions.value = [];
  areaOptions.value = [];
  detailAddress.value = "";

  if (value) {
    try {
      const res = await getChildrenByParentId(value);
      cityOptions.value = res.data.map((item) => ({
        value: item.id,
        label: item.name,
      }));
    } catch (error) {
      console.error("获取城市列表失败:", error);
    }
  }
  updateFullAddress();
};

// 处理城市选择变化
const handleCityChange = async (value) => {
  selectedArea.value = "";
  areaOptions.value = [];

  if (value) {
    try {
      const res = await getChildrenByParentId(value);
      areaOptions.value = res.data.map((item) => ({
        value: item.id,
        label: item.name,
      }));
    } catch (error) {
      console.error("获取区域列表失败:", error);
    }
  }
  updateFullAddress();
};

// 处理区域选择变化
const handleAreaChange = () => {
  updateFullAddress();
};

// 处理详细地址变化
const handleDetailAddressChange = () => {
  updateFullAddress();
};

// 更新完整地址
const updateFullAddress = () => {
  const province =
    provinceOptions.value.find((item) => item.value === selectedProvince.value)
      ?.label || "";
  const city =
    cityOptions.value.find((item) => item.value === selectedCity.value)
      ?.label || "";
  const area =
    areaOptions.value.find((item) => item.value === selectedArea.value)
      ?.label || "";

  const address = [province, city, area, detailAddress.value]
    .filter(Boolean)
    .join(" ");

  form.value.cusColumn2 = address;
  fullAddress.value = address;
};

// 解析地址
const parseAddress = async (address) => {
  if (!address) {
    selectedProvince.value = "";
    selectedCity.value = "";
    selectedArea.value = "";
    detailAddress.value = "";
    fullAddress.value = "";
    return;
  }

  const parts = address.split(" ");

  try {
    // 加载省份数据
    const provinceRes = await getProvinceList();
    provinceOptions.value = provinceRes.data.map((item) => ({
      value: item.id,
      label: item.name,
    }));

    if (parts[0]) {
      const province = provinceOptions.value.find(
        (item) => item.label === parts[0]
      );
      if (province) {
        selectedProvince.value = province.value;

        // 加载城市数据
        const cityRes = await getChildrenByParentId(province.value);
        cityOptions.value = cityRes.data.map((item) => ({
          value: item.id,
          label: item.name,
        }));

        if (parts[1]) {
          const city = cityOptions.value.find(
            (item) => item.label === parts[1]
          );
          if (city) {
            selectedCity.value = city.value;

            // 加载区域数据
            const areaRes = await getChildrenByParentId(city.value);
            areaOptions.value = areaRes.data.map((item) => ({
              value: item.id,
              label: item.name,
            }));

            if (parts[2]) {
              const area = areaOptions.value.find(
                (item) => item.label === parts[2]
              );
              if (area) {
                selectedArea.value = area.value;
              }
            }
          }
        }
      }
    }

    // 设置详细地址
    if (parts.length > 3) {
      detailAddress.value = parts.slice(3).join(" ");
    }

    // 更新完整地址显示
    updateFullAddress();
  } catch (error) {
    console.error("解析地址失败:", error);
  }
};

/** 查询用户列表 */
function getList() {
  loading.value = true;
  listCustomer(queryParams.value).then((response) => {
    customerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    code: null,
    name: null,
    remark: null,
    enable: 1,
    accountingCategoryId: null,
    cusColumn0: null,
    cusColumn1: null,
    cusColumn2: "",
    cusColumn3: null,
    cusColumn4: null,
    cusColumn5: null,
    cusColumn6: null,
    cusColumn7: null,
    cusColumn8: null,
    cusColumn9: null,
    cusColumn10: null,
    cusColumn11: null,
    cusColumn12: null,
    cusColumn13: null,
    cusColumn14: null,
    cusColumn15: null,
  };

  // 重置地址选择器
  selectedProvince.value = "";
  selectedCity.value = "";
  selectedArea.value = "";
  detailAddress.value = "";
  fullAddress.value = "";
  cityOptions.value = [];
  areaOptions.value = [];

  // 重置表单验证
  proxy.$refs["customerRef"]?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
  console.log("选中的行:", selection);
}

// 生成新的客户编码
const generateNewCode = (customerList) => {
  // 如果没有客户数据,从 1 开始
  if (!customerList || customerList.length === 0) {
    return "1";
  }

  // 获取所有编码中的最大数字
  const maxNum = customerList
    .map((item) => {
      // 直接获取数字编码
      return parseInt(item.code) || 0;
    })
    .reduce((max, num) => Math.max(max, num), 0);

  // 生成新编码
  return String(maxNum + 1);
};

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 生成新的客户编码
  form.value.code = generateNewCode(customerList.value);
  open.value = true;
  title.value = "添加客户";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  try {
    const _id = row?.id || ids.value[0];
    const response = await getCustomer(_id);
    form.value = response.data;
    await parseAddress(form.value.cusColumn2);
    open.value = true;
    title.value = "修改客户";
  } catch (error) {
    console.error("获取客户信息失败:", error);
    proxy.$modal.msgError("获取客户信息失败，请重试");
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["customerRef"].validate(async (valid) => {
    if (valid) {
      try {
        // 确保地址已更新
        updateFullAddress();

        // 修改这里的地址验证逻辑
        if (
          !selectedProvince.value ||
          !selectedCity.value ||
          !selectedArea.value ||
          !detailAddress.value
        ) {
          proxy.$modal.msgError("请完整填写地址信息");
          return;
        }

        if (form.value.id != null) {
          await updateCustomer(form.value);
          proxy.$modal.msgSuccess("修改成功");
        } else {
          await addCustomer(form.value);
          proxy.$modal.msgSuccess("新增成功");
        }
        open.value = false;
        getList();
      } catch (error) {
        console.error("提交失败:", error);
        proxy.$modal.msgError(error.message || "操作失败，请重试");
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除用户编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delCustomer(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "customer/customer/export",
    {
      ...queryParams.value,
    },
    `customer_${new Date().getTime()}.xlsx`
  );
}

/** 导入按钮操作 */
function handleImport() {
  importOpen.value = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "customer/customer/importTemplate",
    {},
    `customer_template_${new Date().getTime()}.xlsx`
  );
}

/** 文件超出个数限制 */
function handleExceed() {
  ElMessage.warning("最多只能上传一个文件");
}

/** 文件选择变化 */
function handleFileChange(file) {
  // 检查文件类型
  if (file.raw) {
    const extension = file.raw.name.split(".").pop().toLowerCase();
    if (["xlsx", "xls"].indexOf(extension) < 0) {
      proxy.$modal.msgError("请选择 Excel 文件！");
      uploadRef.value?.clearFiles();
      return false;
    }
    fileList.value = [file.raw];
  }
}

/** 上传文件 */
async function handleUpload(options) {
  const { file } = options;
  const formData = new FormData();
  formData.append("file", file);
  formData.append("updateSupport", "0");

  try {
    // 添加上传进度提示
    const loading = proxy.$loading({
      lock: true,
      text: "正在导入数据，请稍候...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    const response = await importCustomer(formData);
    loading.close();

    if (response.code === 200) {
      proxy.$modal.msgSuccess(response.msg || "导入成功");
      importOpen.value = false;
      getList();
    } else {
      // 显示详细的错误信息
      let errorMsg = response.msg || "导入失败";
      if (response.data && Array.isArray(response.data)) {
        errorMsg += "\n" + response.data.join("\n");
      }
      proxy.$modal.msgError(errorMsg);
    }
  } catch (error) {
    console.error("上传失败:", error);
    // 显示更详细的错误信息
    let errorMsg = "上传失败，请检查文件格式或网络连接";
    if (error.response) {
      switch (error.response.status) {
        case 400:
          errorMsg = "文件格式错误或数据不符合要求";
          break;
        case 413:
          errorMsg = "文件大小超出限制";
          break;
        case 415:
          errorMsg = "不支持的文件类型";
          break;
        case 500:
          errorMsg = "服务器处理失败，请联系管理员";
          break;
      }
      if (error.response.data && error.response.data.msg) {
        errorMsg += "：" + error.response.data.msg;
      }
    }
    proxy.$modal.msgError(errorMsg);
  } finally {
    uploadRef.value?.clearFiles();
  }
}

/** 导入对话框关闭时的处理 */
function handleImportDialogClosed() {
  uploadRef.value?.clearFiles();
  fileList.value = [];
  uploading.value = false;
}

/** 提交上传文件 */
function submitFileForm() {
  if (fileList.value.length === 0) {
    proxy.$modal.msgError("请选择要上传的文件");
    return;
  }
  uploading.value = true;
  uploadRef.value?.submit();
}

// 将汉字转换为拼音首字母
const getFirstLetters = (str) => {
  if (!str) return "";

  // 如果是英文,直接返回小写
  if (/^[a-zA-Z\s]+$/.test(str)) {
    return str.toLowerCase();
  }

  // 如果包含中文,获取每个汉字的首字母
  const pinyin = require("pinyin");
  return pinyin(str, {
    style: pinyin.STYLE_FIRST_LETTER,
    heteronym: false,
  })
    .map((item) => item[0])
    .join("");
};

// 监听客户名称输入,自动生成助记码
const handleNameInput = (value) => {
  form.value.cusColumn0 = getFirstLetters(value);
};

// 添加表格行类名处理函数
const tableRowClassName = ({ row }) => {
  return row.enable === 0 ? "disabled-row" : "";
};

// 处理启用状态变更
const handleEnableChange = (value) => {
  if (value === 0) {
    proxy.$modal
      .confirm("亲，辅助核算项目停用后不能再在凭证中使用哦，是否确认停用？")
      .then(() => {
        // 用户点击确定，保持当前状态
      })
      .catch(() => {
        // 用户点击取消，恢复之前的状态
        form.value.enable = 1;
      });
  }
};

getList();
</script>

<style lang="scss" scoped>
.address-select {
  display: flex;
  .el-select {
    margin-right: 10px;
  }
}

// 添加地址显示框的样式
:deep(.el-input-group__prepend) {
  background-color: var(--el-fill-color-blank);
  color: var(--el-text-color-primary);
}

// 添加停用状态的行样式
:deep(.disabled-row) {
  color: var(--el-text-color-disabled);
  background-color: var(--el-fill-color-light);
}
</style>
